package com.tang.generate.utils

import com.tang.generate.model.req.TableAddReq
import com.tang.generate.model.req.TableFieldReq
import com.tang.generate.model.req.TableIndexReq
import java.util.Objects
import java.util.stream.Collector
import java.util.stream.Collectors

object TableConvert {


    private val tableIdField: TableFieldReq = TableFieldReq(
            name = "id",
            type = "BIGINT",
            javaName = "id",
            javaType = "Long",
            length = 20,
            desc = "id",
            primary = true,
            auto = true,
            notNull = true
    );

    private val tableCommonFieldList: List<TableFieldReq> = listOf(
            TableFieldReq(
                    name = "create_time",
                    type = "datetime",
                    javaName = "createTime",
                    javaType = "LocalDateTime",
                    desc = "创建时间",
            ),
            TableFieldReq(
                    name = "update_time",
                    type = "datetime",
                    javaName = "updateTime",
                    javaType = "LocalDateTime",
                    desc = "更新时间",
            ),
            TableFieldReq(
                    name = "del_flag",
                    type = "char",
                    javaName = "delFlag",
                    javaType = "String",
                    length = 1,
                    charset = "utf8mb4",
                    charsetSort = "utf8mb4_general_ci",
                    desc = "删除标记 2 删除 0 未删除",
            ),
            TableFieldReq(
                    name = "tenant_id",
                    type = "VARCHAR",
                    javaName = "tenantId",
                    javaType = "String",
                    length = 255,
                    charset = "utf8mb4",
                    charsetSort = "utf8mb4_general_ci",
                    desc = "租户id",
            )
    );

    fun getCreateTableSql(tableAddReq: TableAddReq): String {
        val stringBuilder = StringBuilder();
//        stringBuilder.append("DROP TABLE IF EXISTS `${tableAddReq.tableName}`;").append("\n");
        stringBuilder.append("CREATE TABLE `${tableAddReq.tableName}`  (").append("\n");
        val primaryFieldList = arrayListOf<TableFieldReq>();
        tableAddReq.fieldList = listOf(tableIdField).plus(tableAddReq.fieldList!!)
        tableAddReq.fieldList = tableAddReq.fieldList!!.plus(tableCommonFieldList)
        tableAddReq.fieldList!!.forEach {
            stringBuilder.append("  `${it.name}` ${it.type}(${if (it.point!! != 0) "${it.length}, ${it.point}" else "${it.length}"}) ${
                if (it.type.equals("VARCHAR") ||
                        it.type.equals("CHAR") || it.type.equals("TEXT") ||
                        it.type.equals("LONGTEXT")) "CHARACTER SET ${it.charset} COLLATE ${it.charsetSort}  " else ""
            }" +
                    "${if (it.notNull!!) "NOT NULL" else "NULL"} ${
                        if (!it.primary!!)
                            if (it.defaultValue != null)
                                "DEFAULT '${it.defaultValue}'"
                            else "DEFAULT NULL"
                        else ""
                    } ${if (it.auto!!) "AUTO_INCREMENT" else ""} COMMENT '${it.desc}',").append("\n");
            if (it.primary!!) {
                primaryFieldList.add(it);
            }
        }
        primaryFieldList.forEach {
            stringBuilder.append("  PRIMARY KEY (`${it.name}`) USING BTREE");
        }
        tableAddReq.indexList!!.forEach {
            stringBuilder.append(",\n")
            stringBuilder.append("  ${if (it.indexType!! == "UNIQUE") it.indexType else ""}" +
                    "INDEX `${it.indexName}`(`${it.indexField!!.joinToString("`,`")}`) USING " +
                    "${it.indexMethod} COMMENT '${it.desc}'").append("\n")
        }
        stringBuilder.append(") ENGINE = ${tableAddReq.engine} AUTO_INCREMENT = ${tableAddReq.autoIncrement} CHARACTER SET = " +
                "${tableAddReq.charset} COLLATE = ${tableAddReq.charsetSort} COMMENT = '${tableAddReq.desc}' ROW_FORMAT = Dynamic;").append("\n");
        return stringBuilder.toString();
    }


    fun getCreateTableIndexSql(tableIndexList: List<TableIndexReq>, tableName: String, databaseName: String): List<String> {
        return tableIndexList.stream().map {
            return@map "ALTER TABLE `$databaseName`.`$tableName` DROP INDEX `${it.indexName}`," +
                    " ADD ${if (it.indexMethod!! == "UNIQUE") it.indexMethod else ""}" +
                    " INDEX `${it.indexName}`(`${it.indexField!!.joinToString("`,`")}`) USING ${it.indexType} COMMENT '${it.desc}';"
        }.collect(Collectors.toList())
    }

    fun getCreateTableFieldSql(tableFieldReqList: List<TableFieldReq>, tableName: String, databaseName: String): List<String> {
        return tableFieldReqList.stream().map {
            return@map if (it.id != null) {
                "  ALTER TABLE `${databaseName}`.`${tableName}` ${
                    if (it.originName != it.name)
                        "CHANGE COLUMN `${it.originName}` `${it.name}`" else "MODIFY `${it.name}`"
                } " +
                        "${it.type}(${if (it.point!! != 0) "${it.length}, ${it.point}" else "${it.length}"}) ${
                            if (it.type.equals("VARCHAR") ||
                                    it.type.equals("CHAR") || it.type.equals("TEXT") ||
                                    it.type.equals("LONGTEXT")) "CHARACTER SET ${it.charset} COLLATE ${it.charsetSort}" else ""
                        }" +
                        "${if (it.notNull!!) "NOT NULL" else "NULL"} ${
                            if (!it.primary!!)
                                if (it.defaultValue != null)
                                    "DEFAULT '${it.defaultValue}'"
                                else "DEFAULT NULL"
                            else ""
                        } ${if (it.auto!!) "AUTO_INCREMENT" else ""} COMMENT '${it.desc}';"
            } else {
                "ALTER TABLE `${databaseName}`.`${tableName}` ADD COLUMN   `${it.name}` ${it.type}(${if (it.point!! != 0) "${it.length}, ${it.point}" else "${it.length}"}) ${
                    if (it.type.equals("VARCHAR") ||
                            it.type.equals("CHAR") || it.type.equals("TEXT") ||
                            it.type.equals("LONGTEXT")) "CHARACTER SET ${it.charset} COLLATE ${it.charsetSort}" else ""
                } ${if (it.notNull!!) "NOT NULL" else "NULL"} ${
                    if (!it.primary!!)
                        if (it.defaultValue != null)
                            "DEFAULT '${it.defaultValue}'"
                        else "DEFAULT NULL"
                    else ""
                } ${if (it.auto!!) "AUTO_INCREMENT" else ""} COMMENT '${it.desc}';"
            }
        }.collect(Collectors.toList());
    }


    fun getModifyTableName(originTableName: String, tableName: String): String {
        return "alter table $originTableName rename to $tableName;";
    }


}

